/*
 * @Author: wuduiyu 15563365135@163.com
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-09-29 10:02:01
 * @FilePath: \SGCM\src\utils\request.ts
 * @Description:
 * Copyright (c) 2023 by G, All Rights Reserved.
 */

//生成一个axios的拦截器，并判断token是否存在，存在则添加到请求头中，如果返回值为401则跳转到登录页面，如果返回值code 不是200则提示错误信息
import axios from 'axios'
import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import { ElMessage } from 'element-plus'
// const service = axios.create({
//   baseURL: import.meta.env.VITE_API_BASE_PATH as string,
//   timeout: import.meta.env.VITE_BASE_TIMEOUT //限制返回时长
// })
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: parseInt(import.meta.env.VITE_BASE_TIMEOUT || '5000')
})
const userStore = useUserStore()
service.interceptors.request.use((config) => {
  if (userStore.getToken) {
    config.headers['Authorization'] = userStore.getToken
  } else {
    ElMessage.error('token失效，请从新登录')
    router.push('/login')
  }
  return config
})
service.interceptors.response.use((response) => {
  const res = response.data
  if (res.code == 200) {
    return res
  } else if (res.code == 401) {
    ElMessage.error(res.msg)
    // localStorage.clear()
    // router.push('/login');
    userStore.reset()
    return Promise.reject(res.Message || 'error')
  } else {
    ElMessage.error(res.msg)
  }
})

export default service
